package com.xltq.dao.impl;

import com.xltq.dao.IUserDao;
import com.xltq.entity.User;
import com.xltq.utils.C3P0Utils;
import com.xltq.utils.Constants;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.taglibs.standard.lang.jstl.Coercions;

public class IUserDaoImpl implements IUserDao {
    /*
    所有操作中都存在一个小问题,使用DBUtils工具类的时候进行映射时
    列名要和属性名尽量一致, 这样才可以将数据映射进去
    列名和User类属性名字不一致,所以要进行别名修改才可以进行赋值操作
    */

    //提供一个QueryRunner的对象进行书数据库操作
    private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
    @Override
    public User selectUserbyName(String username) throws Exception {
        //1.提供查询语句
        String sql = "select u_id as uid, u_name as username, u_password as upassword,u_email as email, u_sex as usex," +
                " u_status as ustatus, u_code as code, u_role as urole from user where u_name = ?";
        //2.提供查询操作获取User对象
        User user = queryRunner.query(sql, new BeanHandler<User>(User.class), username);
        return user;
    }

    @Override
    public int insertUser(User user) throws Exception {
        //1.提供插入语句
        String sql = "insert into user(u_name, u_password, u_email, u_sex, u_status, u_code, u_role) values(?,?,?,?,?,?,?)";
        //2.提供数据库插入语句
        int rows = queryRunner.update(sql, user.getUsername(), user.getUpassword(), user.getEmail(),
                user.getUsex(), user.getUstatus(), user.getCode(), user.getUrole());
        return rows;
    }

    @Override
    public User selectUserByCode(String code) throws Exception {
        //1.提供查询语句
        String sql = "select u_id as uid, u_name as username, u_password as upassword,u_email as email, u_sex as usex," +
                " u_status as ustatus, u_code as code, u_role as urole from user where u_code = ?";
        //2.提供查询操作获取User对象
        User user = queryRunner.query(sql, new BeanHandler<User>(User.class), code);
        return user;
    }
    //这个方法主要是更新激活装填
    @Override
    public int updateStatusByUid(int uid) throws Exception {
        //1.提供更新语句
        String sql = "update user set u_status = ? where u_id = ?";
       //2.提供更新语句更新表中对应数据
        int rows = queryRunner.update(sql, Constants.USER_ACTIVE, uid);

        return rows;
    }
}
